<template>
	<view class="backview">
		<lexiconNavVue title="| 英语写作 |" />
		<view class="main">
			<view class="top-menu">
				<!-- 键盘监听输入框 -->
				<view class="input-content-back" v-if="platform == 'ios'">
					<input v-model="inputValue" maxlength="1" type="password" class="input-class" :focus='focusState'
						:auto-blur="false" :show-confirm-bar="false" @input="inputChange" @confirm="enterClicked"
						@keydown.enter="enterClicked" inputmode="none"> </input>
					<input v-model="inputValue1" maxlength="1" type="password" class="input-class" :focus='focusState2'
						:auto-blur="false" :show-confirm-bar="false" @input="inputChange" @confirm="enterClicked"
						@keydown.enter="enterClicked" inputmode="none"> </input>
				</view>
			</view>

			<!-- <scroll-view class="message-scroll" :style="{ height: scrollHeight + 'px'}" scroll-y
				:scroll-with-animation='true'> -->
			<view class="message-scroll" :style="{ height: scrollHeight + 'px'}" scroll-y :scroll-with-animation='true'>

				<view class="content-backview">
					<view class="left-view">
						<view class="question-num">
							{{testIndex + 1}}/{{test_list.length}}
						</view>
						<view class="left-airbubble">
							<view class="d1">{{gameInfo.name}}</view>
							<view class="d1">{{gameInfo.en_name}}</view>
							<view v-if="isPad" style="height: 20px;">

							</view>
							<view class="d2">{{gameInfo.content}}</view>
						</view>
						<view class="mifeng">
							<mifeng v-if="canvasheight>0&&isPad==false" ref="uniWordList2"></mifeng>
							<mifengDaren v-if="canvasheight>0&&isPad==true" ref="uniWordList2"></mifengDaren>
						</view>
						<view style="width: 50px; position: absolute;">
							<text class="donghuaType" style="color:#ffffff00;">{{donghua}}</text>
						</view>
					</view>
					<view class="right-view">
						<view class="input">
							<uv-input @blur="fnBlur()" @focus="fnFocus()" customStyle="background:white;"
								placeholder="Title" border="surround" v-model="mine_title"></uv-input>
						</view>
						<view class="textarea">
							<uv-textarea @blur="fnBlur()" @focus="fnFocus()" height="100" v-model="mine_content"
								placeholder="Click to answer the question"></uv-textarea>
						</view>
						<view style="width: 100%;height: 102px;position: relative;margin-top: 5px;"
							title="!!!!!!!!!!!!">
							<view class="bottom-content-one">
								<view class="bottom-content-two">
									<view class="voicebegin-img" v-if="beginRecording">
										<image src="" mode="scaleToFill"
											style="width: 100%; height: 100%; border-radius: 30px;">
										</image>
									</view>
									<view class="voice-back">
										<!-- 进度球 -->
										<view class="water-wave-ball" v-show="beginRecording==true"
											@click="voiceClicked">
											<l-liquid title="进度球" style="width: 76px;height: 76px"
												:style="{zIndex:percent==0?-1:1}" :current.sync="modelVale"
												:percent="percent" :wave-color="color">
												<text title="进度球"
													style="color: white;font-weight: bold; font-size: 20px;">
													{{percentTimes}}
												</text>
											</l-liquid>
										</view>
										<view class="voice-content" @click="voiceClicked" v-show="beginRecording==false"
											:style="{ backgroundImage: 'url(' + longPressImage + ')' }">
										</view>
										<view class="voice-str">
											{{voiceStr}}
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>

				</view>
			</view>
			<!-- </scroll-view> -->
			<view class="bottom-menuview">
				<view class="btn-style" @click="submitFn">
					Submit
				</view>
			</view>
		</view>
		<popPromptBox v-if="showPromptbox" :msg="PromptMsg" @confirm="hidePromptbox"></popPromptBox>
		<selectContentView v-if="showTipPromptbox" :msg="msg" confirmTitle="确认" cancelTitle="取消"
			@confirm="confirmCreate" @cancel="cancelClicked"></selectContentView>
		<keyboardListener v-if="platform == 'android'" @keydown="listenOnKeydown"></keyboardListener>
	</view>
</template>

<script>
	var isIos;
	// #ifdef APP-PLUS
	isIos = plus.os.name == 'iOS';
	// #endif
	import CryptoJS from 'crypto-js';
	import mifeng from '../../components/games/mifeng-daren-phone.vue'
	import mifengDaren from '../../components/games/mifeng-daren-pad.vue'
	import sendVoice from '../txasr/sendVoice.js';
	import {
		string
	} from '../../uni_modules/uv-ui-tools/libs/function/test';
	/** 先引入Recorder （ 需先 npm install recorder-core ）**/
	import Recorder from 'recorder-core'; //注意如果未引用Recorder变量，可能编译时会被优化删除（如vue3 tree-shaking），请改成 import 'recorder-core'，或随便调用一下 Recorder.a=1 保证强引用

	/** 引入RecordApp **/
	import RecordApp from 'recorder-core/src/app-support/app.js'
	//【所有平台必须引入】uni-app支持文件
	import '../../uni_modules/Recorder-UniCore/app-uni-support.js'


	/** 可选：App中引入原生录音插件来进行录音，兼容性和体验更好，原生插件市场地址: https://ext.dcloud.net.cn/plugin?name=Recorder-NativePlugin （试用无任何限制）
		在调用RecordApp.RequestPermission之前进行配置，建议放到import后面直接配置（全局生效）
		也可以判断一下只在iOS上或Android上启用，不判断就都启用，比如判断iOS：RecordApp.UniIsApp()==2 */
	RecordApp.UniNativeUtsPlugin = {
		nativePlugin: true
	}; //目前仅支持原生插件，uts插件不可用
	import keyboardListener from '../games/keyboard-listener.vue'
	const recorderManager = uni.getRecorderManager();
	export default {
		components: {
			mifeng,
			mifengDaren,
			keyboardListener
		},
		data() {
			return {
				canRecord: true,
				hasReceivedMessage: false,
				isResultData: false, //是否显示结果

				// 水波球
				modelVale: 0,
				percent: 100,
				percentTimes: 60,
				percentInterval: null,
				color: "#ffaa00",


				//speech 蓝牙
				isMounted: false,
				recpowerx: 0,
				recpowert: "",
				reclogs: [],
				reclogLast: "",

				test_list: [],
				testIndex: 0,
				gameInfo: {},

				beginRecording: false,
				msg: '',
				isplayVoice: false,
				showTipPromptbox: false,
				canvasheight: 0,
				canvaswidth: 300,
				showPromptbox: false,
				PromptMsg: '',
				beginAiLoad: false,
				start_time: '',
				speechRecognitionString: "", // 接收语音识别的字符串
				audioContext: null, //音频对象
				longPressImage: require('../../static/image/ftalk/voice-nomal.png'),
				resetImage: require('../../static/image/ftalk/voice-nomal.png'),
				voiceStr: 'Tap to start recording.',
				scrollTop: 0,
				scrollHeight: 0,
				secretKey: 'V2X3d8ulhirvtkVFtPygTJa0Nl6bCHVe',
				secretId: 'AKIDDYp3Nf0FR4vpeNzW9gK1oYSMCHONMKNB',
				appId: '1323065199',
				donghua: 'donghua_daiji',
				aievalKey: '',
				webSocketTask: null,
				// 更多参数参考腾讯文档,全部兼容
				defaultData: {
					EngSerViceType: '16k_zh-PY',
					SourceType: 1,
					VoiceFormat: 'mp3',
					Data: '',
					DataLen: null
				},
				isPad: false,
				platform: '',
				// 键盘监听
				focusState: true,
				focusState2: false,
				inputValue: '',
				inputValue1: '',

				mine_title: 'My house',
				mine_content: '',
				reportId: '',
				type_id: '',
				grade_id: '',



			}
		},
		watch: {
			beginRecording(newValue, oldValue) {
				var that = this;
				if (newValue == true) { // 语音识别开始
					that.initAieval();
					that.start_time = new Date().getTime();
					// that.longPressImage = require('../../static/image/ftalk/voice-select.png');
					that.voiceStr = 'Tap to stop recording.';
				} else { // 语音识别结束
					// that.longPressImage = require('../../static/image/ftalk/voice-nomal.png');
					that.voiceStr = 'Tap to start recording.';
					that.recStop();
				}
				if (newValue == false) {
					that.resetPercent();
				} else {
					that.color = "#ffaa00";
					that.percentInterval = setInterval(function() {
						that.addPercent();
					}, 1000)
				}
			}
		},
		onUnload() {
			if ('socket相关') {
				this.hasReceivedMessage = true; // 设置已接收消息标志位
				if (this.webSocketTask) {
					this.webSocketTask.close({
						success: () => {
							console.log('WebSocket 已关闭');
						},
						fail: (res) => {
							console.error('关闭 WebSocket 失败:', res);
						}
					});
					this.webSocketTask = null;
				}
			}


			this.audioContext.destroy(() => {
				console.log('销毁音频上下文对象');
			})
			this.audioContext = null;
			// // #ifdef APP-PLUS
			// plus.screen.lockOrientation('portrait-primary');
			// // #endif
		},
		onLoad(options) {
			var that = this;
			this.getFileList();
			uni.onSocketMessage((res) => {
				if (!this.hasReceivedMessage) {
					console.log('收到服务器回调：' + res.data);
					this.resultData = JSON.parse(res.data);
					uni.hideLoading();
					this.isResultData = true;
					this.webSocketTask.close();
					this.handlingRatings();
				}
			});
			uni.onSocketError((err) => {
				uni.hideLoading();
				console.log('收到服务器Error：' + JSON.stringify(err));
				this.webSocketTask.close();
			});
			uni.onSocketClose((err) => {
				uni.hideLoading();
				console.log('收服务器Close：' + JSON.stringify(err));
			});
			uni.getSystemInfo({
				success: function(res) {
					const platform = res.platform.toLowerCase(); // 全部转化为小写字母 ios/android
					that.platform = platform
				}
			})
			const systemInfo = uni.getSystemInfoSync();
			this.isPad = systemInfo.screenWidth > 600 && systemInfo.pixelRatio < 3;
			if (this.isPad) {
				// // #ifdef APP-PLUS
				// plus.screen.lockOrientation('default');
				// // #endif
			}
			this.type_id = options.type_id
			this.grade_id = options.grade_id
			this.getGameInfo();
		},
		onShow() {
			if (this.isMounted) this.uniPage__onShow(); //onShow可能比mounted先执行，页面可能还未准备好
		},
		onReady() {
			const that = this

			that.$nextTick(function() {
				uni.createSelectorQuery().select('.top-menu').boundingClientRect(rect => {
					that.scrollHeight = uni.getSystemInfoSync().screenHeight - rect.bottom -
						120;
					console.log('that.scrollHeight', that.scrollHeight);
					console.log("that.canvasheight", that.canvasheight)
					setTimeout(function() {
						uni.createSelectorQuery().select('.left-view').boundingClientRect(rect => {
							that.canvasheight = rect.height;
						}).exec();
					}, 500)
				}).exec();
			})
		},
		mounted() {
			var that = this;

			// 判断屏幕宽度和高度，如果超过某个阈值则认为是平板
			if ('判断屏幕宽度和高度，如果超过某个阈值则认为是平板') {
				const systemInfo = uni.getSystemInfoSync();
				this.isPad = systemInfo.screenWidth > 600 && systemInfo.pixelRatio < 3;
				console.log('ispadddddd', this.isPad)
			}

			that.audioContext = uni.createInnerAudioContext();
			that.audioContext.volume = that.fayinguan_volume_value;
			// 监听错误事件
			that.audioContext.onError((res) => {
				console.error('音频加载或播放错误1', res);
				//MediaError（媒体错误）：表示音频播放过程中出现了媒体相关的错误。
				if (res && res.errMsg == 'MediaError') {

				}
				// SrcError（资源路径错误）：表示音频资源路径设置不正确的错误
				if (res && res.errMsg == 'SrcError') {
					uni.showToast({
						title: 'SrcError，请重试~',
						icon: 'error'
					})
				}
			});
			// 监听音频开始播放事件
			that.audioContext.onPlay(() => {
				that.donghua = 'donghua_shuohua';
			});
			// 监听播放中事件
			that.audioContext.onTimeUpdate(() => {});
			// 监听音频播放完毕事件
			that.audioContext.onEnded(() => {
				that.donghua = 'donghua_daiji';
				// that.getFileList();
			});
		},
		/*#ifdef VUE3*/
		unmounted() /*#endif*/ /*#ifndef VUE3*/ destroyed() /*#endif*/ {
			RecordApp.Stop(); //清理资源，如果打开了录音没有关闭，这里将会进行关闭
		},
		methods: {
			fnBlur() {
				this.canRecord = true;
				uni.showToast({
					title: "fnBlur"
				})
			},
			fnFocus() {
				this.canRecord = false;
				uni.showToast({
					title: "fnFocus"
				})
			},


			fnChangeTitle() {

			},

			// 获取题数据
			getGameInfo() {
				this.$http.ajax_test_list({
					type_id: this.type_id,
					grade_id: this.grade_id
				}).then(res => {
					console.log('res', res);
					if (res.code == 200) {
						this.reportId = res.data.test_card_info.id
						this.test_list = res.data.test_list
						this.gameInfo = this.test_list[0]
						this.mine_title = this.gameInfo.content
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						})
					}
				})
			},

			submitFn() {
				var that = this;
				uni.showLoading({
					title: 'AI语音智能评测中...',
				})
				this.$http.submitEng({
					test_user_id: this.gameInfo.test_user_id,
					mine_title: this.mine_title,
					mine_content: this.mine_content
				}).then(res => {
					uni.hideLoading()
					if (res.code === 200) {
						uni.redirectTo({
							url: `/pages/bmaster/report/report_yyxz?id=${this.reportId}`
						})
					}
				})
			},

			addPercent() {
				var that = this;
				that.percentTimes--;
				if (that.percentTimes == 0) {
					that.resetPercent();
					return false;
				} else {
					if (that.percentTimes >= 20) {
						that.percent -= 1.66;
						that.color = "#ffaa00";
					} else {
						that.color = "#ffaa00";
						that.percent -= 1.66;
					}
				}
			},

			resetPercent() {
				var that = this;
				that.beginRecording = false;
				that.color = "#ffaa00";

				clearInterval(that.percentInterval)
				that.percentInterval = null;
				that.percentTimes = 60;
				that.percent = 100;
			},
			// 处理评分
			handlingRatings() {
				var that = this;
				var scoreData = that.resultData.result.overall;
				console.log('scoreData', scoreData);
				if (scoreData > 79 && scoreData < 101) {
					that.donghua = 'donghua_jubei';
				} else if (scoreData > 59 && scoreData < 80) {
					that.donghua = 'donghua_bixin';
				} else if (scoreData > 39 && scoreData < 60) {
					that.donghua = 'donghua_keai';
				} else if (scoreData > 19 && scoreData < 40) {
					that.donghua = 'donghua_fanu';
				} else if (scoreData > -1 && scoreData < 20) {
					that.donghua = 'donghua_ku';
				}
				// var scoreData = that.resultData.result.overall;
				// console.log('scoreData', scoreData);
				// switch (that.resultData.result.overall) {
				// 	case scoreData > 79 && scoreData < 101:
				// 		that.donghua = 'donghua_jubei';
				// 		break;
				// 	case scoreData > 59 && scoreData < 80:
				// 		that.donghua = 'donghua_bixin';
				// 		break;
				// 	case scoreData > 39 && scoreData < 60:
				// 		that.donghua = 'donghua_keai';
				// 		break;
				// 	case scoreData > 19 && scoreData < 40:
				// 		that.donghua = 'donghua_fanu';
				// 		break;
				// 	case scoreData > -1 && scoreData < 20:
				// 		that.donghua = 'donghua_ku';
				// 		break;
				// 	default:
				// 		break;
				// }
				// var that = this;
				// console.log('that.resultData', that.resultData.audioUrl);
				// // 下载文件到本地
				// uni.downloadFile({
				// 	url: 'http://' + that.resultData.audioUrl, // 要下载的文件地址
				// 	success: (downloadRes) => {
				// 		console.log('downloadRes============', downloadRes);
				// 		if (downloadRes.statusCode === 200) {
				// 			// 下载成功，将文件保存到本地
				// 			uni.saveFile({
				// 				tempFilePath: downloadRes.tempFilePath,
				// 				success: (saveRes) => {
				// 					console.log('saveRes', saveRes);
				// 				},
				// 				fail: (error) => {
				// 					console.error('保存文件失败：', error);
				// 				}
				// 			});
				// 		} else {
				// 			console.error('下载文件失败，状态码：', downloadRes.statusCode);
				// 		}
				// 	},
				// 	fail: (error) => {
				// 		console.error('下载文件失败：', error);
				// 	}
				// });
			},
			// 手动点击下一题
			rightMenuClicked() {
				this.testIndex += 1;
				if (this.testIndex > this.test_list.length) {
					console.log('结束了，跳转结果页')
				} else {
					this.initGameInfo(this.testIndex);
				}
			},
			initGameInfo(testIndex) {
				this.donghua = 'donghua_daiji';
				this.isResultData = false;
				this.gameInfo = this.test_list[testIndex];
			},
			// 键盘监听方法Start==========================
			inputChange: function(event) {
				var value = event.target.value;
				var that = this;
				if (value.includes(" ")) {
					that.voiceClicked();
					setTimeout(function() {
						that.inputValue = '';
						that.inputValue1 = '';
					}, 50);
				}
			},
			// 全局监听外接键盘点击按下事件
			listenOnKeydown(value) {
				if (this.platform === 'android') {
					var that = this;
					if (value.key == " ") { // 语音识别开始
						if (this.canRecord) {
							uni.showToast({
								title: '切换录音'
							})
							this.voiceClicked();
						}
					}
				}
			},
			// 重新录音点击事件
			resetVoice() {
				this.isResultData = false;
				this.longPressImage = require('../../static/image/ftalk/voice-nomal.png');
				this.voiceStr = 'Tap to start recording.';
				this.speechRecognitionString = '';
				this.recStop();
			},
			// enter 点击事件
			enterClicked() {
				uni.hideKeyboard(); //隐藏软键盘	
				if (this.focusState == true) {
					this.focusState = false;
					this.$nextTick(function() {
						this.focusState2 = true;
					});
				} else {
					this.focusState2 = false;
					this.$nextTick(function() {
						this.focusState = true;
					});
				}
			},
			initAieval() {
				const a = this.$statusCode.aievalAppKey; // chivox appKey
				const b = this.$statusCode.aievalSecretKey; // chivox secretKey
				const timestamp = Date.now()
				let buf = CryptoJS.SHA256(a + timestamp + b);
				let verificationJson = '{"app":{"applicationId":"' + a + '", "sig": "' + buf.toString(CryptoJS.enc
						.Hex) +
					'","alg": "sha256","timestamp":"' + timestamp + '", "userId": "chivoxUni"}}';
				// console.log("发送验证信息请求。"+verificationJson);
				this.webSocketTask = uni.connectSocket({
					url: "wss://cloud.chivox.com/ws?e=0&t=0&version=2",
					success: (res) => {
						console.log("连接成功" + JSON.stringify(res));
					},
					fail(res) {
						console.log('连接失败' + JSON.stringify(res));
					}
				});
				this.webSocketTask.onOpen((res) => {
					this.webSocketTask.send({
						// data: verificationJson //json 格式的验证信息
						data: JSON.stringify({
							"app": {
								"applicationId": a.toString(),
								"sig": buf.toString(CryptoJS.enc.Hex),
								"alg": "sha256",
								"timestamp": timestamp.toString(),
								"userId": "chivox001"
							}
						}), //json 格式的验证信息
						success: (res) => {
							console.log("发送签名成功" + JSON.stringify(res));
						},
						fail(res) {
							console.log('发送签名失败' + JSON.stringify(res));
						} //json 格式的验证信息
					})

				})
				this.recStart();
			},
			// START ------ speech 录音（蓝牙耳机收音）
			uniPage__onShow() { //页面onShow时【必须调用】的函数，传入当前组件this
				RecordApp.UniPageOnShow(this);
			},


			// 请求权限
			recReq() {
				this.reclog("正在请求录音权限...");
				RecordApp.UniWebViewActivate(this); //App环境下必须先切换成当前页面WebView
				RecordApp.RequestPermission(() => {
					this.reclog("已获得录音权限，可以开始录音了", 2);
					this.recStart()
				}, (msg, isUserNotAllow) => {
					if (isUserNotAllow) { //用户拒绝了录音权限
						//这里你应当编写代码进行引导用户给录音权限，不同平台分别进行编写
						this.showAuthTip()
					}
					this.reclog(
						(isUserNotAllow ? "isUserNotAllow," : "") + "请求录音权限失败：" + msg, 1);
				});
			},

			showAuthTip() {
				// 提示弹窗
				this.confirmTipShow = true
				this.confirmTipMsg = 'App需要您的同意，才能访问麦克风进行语音识别转换/录制音频，如禁止将无法识别语音转换/录制音频发送，请在“设置”中允许“拼词之星”访问麦克风'
				this.confirmTipConfirmText = '确定'
				this.confirmTipCancelText = ''
			},

			// 开始录音
			recStart() {
				var that = this;

				that.luyin_count = 0;
				that.bigBytes = new Uint8Array(0)

				var file = Date.now() + ".mp3";
				this.filePath = "";

				RecordApp.UniWebViewActivate(this); //App环境下必须先切换成当前页面WebView
				RecordApp.Start({
					type: "mp3",
					sampleRate: 16000,
					bitRate: 16,
					onProcess: (buffers, powerLevel, duration, sampleRate, newBufferIdx, asyncEnd) => {
						this.recpowerx = powerLevel;
						this.recpowert = duration + " / " + powerLevel;
					},
					onProcess_renderjs: `function(buffers,powerLevel,duration,sampleRate,newBufferIdx,asyncEnd){
						//App中是在renderjs中进行的可视化图形绘制
						if(this.waveView){
							this.waveView.input(buffers[buffers.length-1],powerLevel,sampleRate);
						}
					}`,
					takeoffEncodeChunk: (chunkBytes) => {
						that.luyin_count++;
						if ('base64音频文件专用') {
							var temp = new Uint8Array(chunkBytes.length + that.bigBytes.length)
							temp.set(that.bigBytes);
							temp.set(chunkBytes, that.bigBytes.length);
							that.bigBytes = temp
						}
					},
					start_renderjs: `function(){
						//App中可以放一个函数，在Start成功时renderjs中会先调用这里的代码，this是renderjs模块的this（也可以用This变量）
						//放一些仅在renderjs中才生效的事情，比如初始化，不提供也行
					}`,
					stop_renderjs: `function(aBuf,duration,mime){
						//App中可以放一个函数，在Stop成功时renderjs中会先调用这里的代码，this是renderjs模块的this（也可以用This变量）
						this.audioData=aBuf; //留着给Stop时进行转码成wav播放
					}`
				}, () => {
					this.reclog("录制中", 2);


					//创建音频可视化图形绘制，App环境下是在renderjs中绘制，H5、小程序等是在逻辑层中绘制，因此需要提供两段相同的代码（宽高值需要和canvas style的宽高一致）
					RecordApp.UniFindCanvas(this, [".recwave-WaveView"], `
						this.waveView=Recorder.WaveView({compatibleCanvas:canvas1, width:300, height:100});
					`, (canvas1) => {
						this.waveView = Recorder.WaveView({
							compatibleCanvas: canvas1,
							width: 300,
							height: 100
						});
					});
				}, (msg) => {
					this.reclog("开始录音失败：" + msg, 1);
				});
			},

			// 停止录音
			recStop() {
				const that = this
				RecordApp.Stop((aBuf, duration, mime) => {
					that.base64 = uni.arrayBufferToBase64(that.bigBytes.buffer)
					that.fnSaveMp3();
					that.end_time = new Date().getTime();
					var diff_time = that.end_time - that.start_time;
					if (that.end_time - that.start_time < 1000) {
						uni.showToast({
							title: '录音时长太短',
							icon: 'error'
						})
					} else {
						that.beginAiLoad = true;
						uni.showLoading({
							title: 'AI语音智能评测中...',
						})
						that.fn_tx_asr();
					}
				}, (msg) => {
					that.reclog("结束录音失败：" + msg, 1);
				});
			},

			fnSaveMp3() {
				var that = this;
				const params = {
					base64: that.base64,
					test_user_id: that.gameInfo.test_user_id
				}
				that.$http.saveMp3Info(params).then(res => {
					if (res.code === 200) {
						console.log('MP3保存成功')
					}
				})
			},

			// 腾讯一句话 uniapp
			async fn_tx_asr() {
				var that = this;
				// base64录音内容
				that.defaultData.Data = that.base64;
				// 录音长度
				that.defaultData.DataLen = uni.base64ToArrayBuffer(that.base64).byteLength;
				// 一句话识别返回结果
				const res = await sendVoice({
					secretId: that.secretId,
					secretKey: that.secretKey,
					payload: that.defaultData
				});
				var content = res.Response.Result;
				console.log('语音翻译内容content==========', content);
				setTimeout(function() {
					if (content) {
						that.mine_content = content;
						that.speechRecognitionString = content;
						uni.hideLoading()
					}
				}, 100)
			},

			reclog(msg, color) {
				var now = new Date();
				var t = ("0" + now.getHours()).substr(-2) +
					":" + ("0" + now.getMinutes()).substr(-2) +
					":" + ("0" + now.getSeconds()).substr(-2);
				var txt = "[" + t + "]" + msg;
				console.log(txt);
				this.reclogs.splice(0, 0, {
					txt: txt,
					color: color
				});
				this.reclogLast = {
					txt: txt,
					color: color
				};
			},
			// END ------ speech 录音（蓝牙耳机收音）

			// 发送评分请求
			sendRatingRequest() {
				let Request_Param = {
					"coreType": "en.prtl.exam",
					"rank": 100,
					"precision": 1,
					"attachAudioUrl": 1,
					"keyWords": this.gameInfo.test_info.keywords_list,
					"refText": {
						"lm": this.gameInfo.test_info.answers_list,
					},
					"userId": "chivox001",
					"result": {
						"details": {
							"use_inherit_rank": 1
						}
					}
				}
				let eval_Param = '{"tokenId":"58d9bc0942dae7072c000001","request":' + JSON.stringify(Request_Param) +
					',"audio":{"sampleBytes":2, "channel":1,"sampleRate":"16000","audioType":"mp3"} }';
				this.webSocketTask.send({
					data: eval_Param,
					success: (res) => {
						console.log("发送评分请求成功" + JSON.stringify(res));
						this.upload();
					},
					fail(res) {
						console.log("发送评分请求失败" + JSON.stringify(res));
					}
				})
			},
			base64ToBinary(base64Str) {
				// 将base64字符串转换为二进制字符串
				let binaryStr = atob(base64Str);
				// 将二进制字符串转换为TypedArray
				let len = binaryStr.length;
				let bytes = new Uint8Array(len);
				for (let i = 0; i < len; i++) {
					bytes[i] = binaryStr.charCodeAt(i);
				}
				// 返回二进制数据流
				return bytes.buffer;
			},
			// 发送音频数据
			upload() {
				let binaryData = this.base64ToBinary(this.base64); //分割base64字符串，取编码部分转二进制数据流
				this.webSocketTask.send({
					data: binaryData,
					success: (res) => {
						console.log("sendAudio:" + JSON.stringify(res));
					},
					fail: (err) => {
						console.log("sendAudioErr:" + JSON.stringify(err));
					}
				});
				this.webSocketTask.send({
					data: '{"cmd":"stop"}',
					success: (res) => {
						console.log("fass" + JSON.stringify(res));
					}
				});
			},
			// 去设置界面开启麦克风权限
			confirmCreate() {
				this.showTipPromptbox = false;
				if (isIos) {
					plus.runtime.openURL("app-settings://")
				} else {
					var Intent = plus.android.importClass("android.content.Intent");
					var Settings = plus.android.importClass("android.provider.Settings");
					var Uri = plus.android.importClass("android.net.Uri");
					var mainActivity = plus.android.runtimeMainActivity();
					var intent = new Intent();
					intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
					var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
					intent.setData(uri);
					mainActivity.startActivity(intent);
				}
			},
			// 未授权麦克风点击事件
			cancelClicked() {
				this.showTipPromptbox = false;
				uni.navigateBack();
			},
			getFileList() {
				uni.getSavedFileList({
					success: (res) => {
						res.fileList.forEach(file => {
							// 使用uni.removeSavedFile删除指定的文件
							uni.removeSavedFile({
								filePath: file.filePath,
								success: function() {
									console.log('文件删除成功');
								},
								fail: function(err) {
									console.error('文件删除失败', err);
								}
							});
						});
					},
					fail: (err) => {}
				})
			},
			// 获取权限
			voiceClicked() {
				if (!this.canRecord) {
					uni.showToast({
						title: '不能录音'
					})
					return false;
				}


				if (this.beginRecording == true) {
					this.beginRecording = false;
				} else {
					RecordApp.UniWebViewActivate(this); //App环境下必须先切换成当前页面WebView
					RecordApp.RequestPermission(() => {
						this.beginRecording = true;
					}, (msg, isUserNotAllow) => {
						if (isUserNotAllow) { //用户拒绝了录音权限
							//这里你应当编写代码进行引导用户给录音权限，不同平台分别进行编写
							this.beginRecording = false
							this.msg = '使用该功能需要您开启麦克风权限，是否去开启？';
							this.showTipPromptbox = true;
						}
					});
				}
			},
			hidePromptbox() {
				this.showPromptbox = false;
			}
		}
	}
</script>
<!-- #ifdef APP -->
<script module="testMainVue" lang="renderjs">
	/**============= App中在renderjs中引入RecordApp，这样App中也能使用H5录音、音频可视化 =============**/
	/** 先引入Recorder **/
	import Recorder from 'recorder-core'; //注意如果未引用Recorder变量，可能编译时会被优化删除（如vue3 tree-shaking），请改成 import 'recorder-core'，或随便调用一下 Recorder.a=1 保证强引用

	//按需引入需要的录音格式编码器，用不到的不需要引入，减少程序体积；H5、renderjs中可以把编码器放到static文件夹里面用动态创建script来引入，免得这些文件太大
	import 'recorder-core/src/engine/mp3.js'
	import 'recorder-core/src/engine/mp3-engine.js'
	import 'recorder-core/src/engine/wav.js'
	import 'recorder-core/src/engine/pcm.js'

	//可选引入可视化插件
	import 'recorder-core/src/extensions/waveview.js'
	import 'recorder-core/src/extensions/wavesurfer.view.js'

	import 'recorder-core/src/extensions/frequency.histogram.view.js'
	import 'recorder-core/src/extensions/lib.fft.js'

	/** 引入RecordApp **/
	import RecordApp from 'recorder-core/src/app-support/app.js'
	//【必须引入】uni-app支持文件
	import '../../uni_modules/Recorder-UniCore/app-uni-support.js'

	export default {
		mounted() {
			//App的renderjs必须调用的函数，传入当前模块this
			RecordApp.UniRenderjsRegister(this);
		},
		methods: {
			//这里定义的方法，在逻辑层中可通过 RecordApp.UniWebViewVueCall(this,'this.xxxFunc()') 直接调用
			//调用逻辑层的方法，请直接用 this.$ownerInstance.callMethod("xxxFunc",{args}) 调用，二进制数据需转成base64来传递
		}
	}
</script>
<!-- #endif -->
<style lang="less">
	.backview {
		background: radial-gradient(circle, #373632, #000);
		width: 100%;
		height: 100vh;
		text-align: center;
	}

	.main {
		width: 100%;
		height: 100vh;
		display: flex;
		position: relative;
		flex-direction: column;
		background-image: url(../../static/image/homePage/diwen.png);
		background-size: 100% auto;
		background-position: top left;
		background-repeat: repeat-y;
		box-sizing: border-box;
	}

	.sentences-class {
		width: 96%;
		margin-left: 2%;
		padding: 15px;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: white;

		// box-shadow: 5px 5px 5px #a3a8b0;
		.sentences-title {
			font-size: 14px;
			color: black;
			text-align: left;
		}

		.sentences-img {
			width: 96%;
			margin-top: 10px;
			height: 100px;
		}
	}

	.resultData {
		width: 96%;
		margin-left: 2%;
		padding-bottom: 15px;
		background-color: white;
		border-radius: 5px;
		display: flex;
		flex-direction: column;

		.result-head {
			width: 100%;
			height: 40px;
			text-align: left;
			font-size: 14px;
			background-color: #dcdcdc;
			color: black;
			line-height: 40px;
			padding-left: 15px;
			box-sizing: border-box;
		}

		.result-num-view {
			width: 100%;
			display: flex;
			padding-top: 10px;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			.result-num {
				width: 90px;
				height: 100px;
				background-image: url(../../static/image/start.png);
				background-repeat: no-repeat;
				background-size: 100% 100%;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				color: white;

				.result-str {
					font-size: 14px;
					color: white;
				}

				.result-num-str {
					font-size: 15px;
					color: white;
					font-weight: 600;
				}
			}

			.result-bottom {
				display: flex;
				padding: 5px 0px;
				flex-direction: row;
				align-items: center;
				justify-content: center;

				.ruselt-bottom-str {
					font-size: 13px;
					color: black;
				}
			}
		}

		.titleview {
			width: 80px;
			height: 25px;
			margin-top: 10px;
			line-height: 25px;
			background-color: #0081ff;
			color: white;
			font-size: 13px;
			margin-left: 10px;
			text-align: center;
			border-top-left-radius: 10px;
			border-bottom-right-radius: 10px;
		}

		.Answer-backview {
			width: 88%;
			margin-top: 10px;
			margin-left: 6%;
			padding: 10px;
			box-sizing: border-box;
			background-color: #fef4d5;
			font-size: 12px;
			color: black;
			text-align: left;
		}

		.otherAnalysis-backview {
			width: 92%;
			margin-top: 10px;
			margin-left: 4%;
			padding: 0px 10px;
			box-sizing: border-box;

			.otherAnalysis-line {
				width: 100%;
				height: 30px;
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: space-between;

				.line-left-str {
					font-size: 14px;
					color: #000;
				}

				.line-right-img {
					width: 24px;
					height: 24px;
				}
			}
		}
	}

	.top-menu {
		width: 100%;
		height: 1px;

		.input-content-back {
			width: 100px;
			height: 1px;
			position: absolute;
			top: -200px;

			.input-class {
				width: 100px;
				height: 10px;
			}
		}
	}

	.message-scroll {
		width: 100%;



		.content-backview {
			width: 100%;
			height: 100%;
			padding: 0px 20px;
			// background: green;
			display: flex;
			flex-direction: column;
			justify-content: space-around;

			.left-view {
				flex: 1;
				width: 100%;
				display: flex;
				flex-direction: column;
				align-items: center;
				// justify-content: flex-end;

				.question-num {
					font-size: 16px;
					color: white;
					height: 50px;
					line-height: 50px;
					width: 100%;
					text-align: center;
				}

				.left-airbubble {
					width: 100%;
					padding: 10px 20px;
					color: black;
					font-weight: bold;
					border-radius: 15px;
					background: white;
					text-align: left;

					.d1 {
						font-size: 14px;
					}

					.d2 {
						font-size: 28px;
					}
				}

				.mifeng {
					width: 100%;
					height: 100%;
				}

			}

			.right-view {
				width: 100%;
				overflow: hidden;
				background-color: #fff;
				padding: 20px 20px;
				padding-bottom: 10px;
				border-radius: 24px;

				.input {
					margin-bottom: 10px;
				}

				.textarea {}
			}
		}
	}

	.chat-container {
		display: flex;
		width: 100%;
		flex-direction: column;
		gap: 20px;
	}

	.bottom-menuview {
		height: 120px;
		box-sizing: border-box;
		// padding-top: 30px;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;

		.bottom-content-one {
			width: 100%;
			height: 150px;
			overflow: hidden;
			background: linear-gradient(to bottom, #e3b75f, #feef7e);
			padding: 3px;
			border-radius: 30px;

			.bottom-content-two {
				width: 100%;
				height: 100%;
				position: relative;
				background: #000;
				border-radius: 30px;
			}
		}
	}

	.bottom-backview {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: row;
		align-items: center;

		.bottom-reset {
			width: 150px;
			height: 100%;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
		}

		.bottom-resultstr {
			flex: 1;
			font-size: 16px;
			text-align: left;
			margin-top: 5px;
			color: white;
		}

		.bottom-rightMenu {
			width: 150px;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;

			.menuview {
				width: 120px;
				height: 60px;
				background: linear-gradient(to bottom, #e3b75f, #feef7e);
				line-height: 60px;
				text-align: center;
				font-size: 16px;
				color: black;
				font-weight: 800;
				border-top-right-radius: 30px;
				border-top-left-radius: 8px;
				border-bottom-right-radius: 30px;
				border-bottom-left-radius: 8px;
			}
		}
	}

	.voicebegin-img {

		width: 100%;
		height: 120px;
		// z-index: -1;
	}

	.voice-back {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		image {
			width: 75px;
			height: 75px;
		}

		.voice-content {
			width: 75px;
			height: 76px;
			background-size: 100% 100%;
			background-position: center center;
			background-repeat: no-repeat;
		}

		.voice-str {
			width: 100%;
			font-size: 12px;
			font-weight: 800;
			text-align: center;
			color: #ccc;
			// margin: 20px;
		}
	}

	.water-wave-ball {
		width: 78px;
		height: 78px;
		background-color: black;
		border-radius: 40px;
		display: flex;
		align-items: center;
		justify-content: center;
		border: 2px solid #ffaa00;
	}

	.result-voice-back {
		width: 140px;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.result-voice-content {
			width: 75px;
			height: 76px;
			background-size: 100% 100%;
			background-position: center center;
			background-repeat: no-repeat;
		}

		.result-voice-str {
			width: 100%;
			font-size: 12px;
			margin-top: 10px;
			font-weight: 800;
			text-align: center;
			color: white;
		}
	}

	.right-image-class {
		height: 300px;
		border-radius: 20px;
		border: 2px solid white;
		-webkit-border-radius: 20px;
		-moz-border-radius: 20px;

		.image {
			border-radius: 20px;
		}
	}

	.btn-style {
		width: 180px;
		height: 100px;
		font-size: 18px;
		background-image: url(/static/image/fdr/submit.png);
		background-size: contain;
		background-repeat: no-repeat;
		background-position: center;
		display: flex;
		align-items: center;
		justify-content: center;
		color: black;
		font-family: hzgb;

	}
</style>